import app from '@system.app';
import device from '@system.device';
import router from '@system.router';
import prompt from '@system.prompt';
import * as wordService from '../../common/wordService.js';
import * as syncService from '../../common/syncService.js';
import * as userService from '../../common/userService.js';

// 示例单词数据
const SAMPLE_WORDS = [
  { word: 'apple', phonetic: '/ˈæpl/', meaning: 'n. 苹果' },
  { word: 'banana', phonetic: '/bəˈnɑːnə/', meaning: 'n. 香蕉' },
  { word: 'orange', phonetic: '/ˈɒrɪndʒ/', meaning: 'n. 橙子；adj. 橙色的' },
  { word: 'grape', phonetic: '/ɡreɪp/', meaning: 'n. 葡萄' },
  { word: 'watermelon', phonetic: '/ˈwɔːtəmelən/', meaning: 'n. 西瓜' }
];

// 同步频率选项
const SYNC_FREQUENCIES = ['每次启动', '每小时', '每天一次', '仅手动同步'];

// 生成复习题目
function generateReviewQuestions(words) {
  if (!words || words.length === 0) return [];
  
  const reviewQuestions = [];
  
  words.forEach(word => {
    // 为每个单词创建一个问题
    const options = [];
    // 正确选项是当前单词的意思
    options.push(word.meaning);
    
    // 添加两个错误选项（从其他单词中随机选择）
    let availableWords = words.filter(w => w.word !== word.word);
    for (let i = 0; i < 2 && availableWords.length > 0; i++) {
      const randomIndex = Math.floor(Math.random() * availableWords.length);
      options.push(availableWords[randomIndex].meaning);
      availableWords.splice(randomIndex, 1);
    }
    
    // 打乱选项顺序
    shuffleArray(options);
    
    reviewQuestions.push({
      word: word.word,
      correctMeaning: word.meaning,
      options: options,
      correctIndex: options.indexOf(word.meaning)
    });
  });
  
  return reviewQuestions;
}

// 打乱数组顺序
function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
}

export default {
    data: {
        currentWord: {},
        wordIndex: 0,
        stats: {
            learned: 0,
            toReview: 0,
            streakDays: 0,
            totalWords: 0,
            masteredWords: 0
        },
        deviceInfo: {},
        isConnectedToPhone: false,
        isLoading: true,
        isLoggedIn: false,
        username: '游客',
        
        // 复习相关数据
        reviewWords: [],
        currentReviewWord: {},
        currentReviewIndex: 0,
        reviewScore: 0,
        
        // 设置相关数据
        settings: {
            dailyGoal: 10,
            reminderEnabled: true,
            darkMode: true,
            syncFrequency: '每天一次',
            syncFrequencyIndex: 2
        }
    },
    
    async onInit() {
        // 获取设备信息
        device.getInfo({
            success: (data) => {
                this.deviceInfo = data;
                console.info('设备信息: ' + JSON.stringify(data));
            },
            fail: (error) => {
                console.error('获取设备信息失败: ' + JSON.stringify(error));
            }
        });
        
        // 检查用户登录状态
        this.isLoggedIn = await userService.isLoggedIn();
        
        if (this.isLoggedIn) {
            // 获取用户名
            this.username = await userService.getUsername();
            
            // 获取学习统计
            await this.loadUserStats();
        }
        
        // 检查是否需要同步
        if (await syncService.checkSyncNeeded()) {
            this.syncWithPhone();
        }
        
        this.isLoading = false;
    },
    
    async loadUserStats() {
        try {
            const stats = await wordService.getStudyStats();
            
            // 更新统计信息
            this.stats.learned = stats.todayNewWords || 0;
            this.stats.toReview = stats.todayReviewWords || 0;
            this.stats.streakDays = stats.streakDays || 0;
            this.stats.totalWords = stats.totalStudiedWords || 0;
            this.stats.masteredWords = stats.masteredWords || 0;
        } catch (error) {
            console.error('获取用户统计失败:', error);
        }
    },
    
    // 开始学习新单词
    startNewWordsStudy() {
        if (!this.isLoggedIn) {
            prompt.showToast({
                message: '请先登录',
                duration: 2000
            });
            return;
        }
        
        router.push({
            uri: '../wordStudy/wordStudy',
            params: {
                isReviewMode: 'false',
                extraNewWords: '0',
                extraReviewWords: '0'
            }
        });
    },
    
    // 开始复习单词
    startReviewWordsStudy() {
        if (!this.isLoggedIn) {
            prompt.showToast({
                message: '请先登录',
                duration: 2000
            });
            return;
        }
        
        router.push({
            uri: '../wordStudy/wordStudy',
            params: {
                isReviewMode: 'true',
                extraNewWords: '0',
                extraReviewWords: '0'
            }
        });
    },
    
    // 开始额外学习
    startExtraStudy(extraNewWords, extraReviewWords) {
        if (!this.isLoggedIn) {
            prompt.showToast({
                message: '请先登录',
                duration: 2000
            });
            return;
        }
        
        router.push({
            uri: '../wordStudy/wordStudy',
            params: {
                isReviewMode: extraNewWords > 0 ? 'false' : 'true',
                extraNewWords: extraNewWords.toString(),
                extraReviewWords: extraReviewWords.toString()
            }
        });
    },
    
    async syncWithPhone() {
        prompt.showToast({
            message: '正在同步...',
            duration: 2000
        });
        
        try {
            const syncResult = await syncService.syncWithPhone();
            
            if (syncResult.success) {
                // 更新统计信息
                if (syncResult.stats) {
                    this.stats.learned = syncResult.stats.todayNewWords || 0;
                    this.stats.toReview = syncResult.stats.todayReviewWords || 0;
                    this.stats.streakDays = syncResult.stats.streakDays || 0;
                    this.stats.totalWords = syncResult.stats.totalStudiedWords || 0;
                    this.stats.masteredWords = syncResult.stats.masteredWords || 0;
                }
                
                prompt.showToast({
                    message: '同步成功',
                    duration: 1000
                });
                
                this.isConnectedToPhone = true;
            } else {
                prompt.showToast({
                    message: '同步失败: ' + (syncResult.message || '未知错误'),
                    duration: 2000
                });
            }
        } catch (error) {
            console.error('同步失败:', error);
            prompt.showToast({
                message: '同步失败，请检查网络连接',
                duration: 2000
            });
        }
    },
    
    // 登录页面
    goToLogin() {
        router.push({
            uri: '../login/login'
        });
    },
    
    // 打开个人信息页面
    goToProfile() {
        if (!this.isLoggedIn) {
            this.goToLogin();
            return;
        }
        
        router.push({
            uri: '../profile/profile'
        });
    },
    
    loadWords() {
        // 在实际应用中，可以从存储或服务器加载单词
        // 这里使用示例数据
        if (SAMPLE_WORDS.length > 0) {
            this.currentWord = SAMPLE_WORDS[this.wordIndex];
            this.stats.toReview = SAMPLE_WORDS.length;
        }
    },
    
    generateReviewWords() {
        // 生成复习题目
        this.reviewWords = generateReviewQuestions(SAMPLE_WORDS);
        if (this.reviewWords.length > 0) {
            this.currentReviewWord = this.reviewWords[this.currentReviewIndex];
        }
    },
    
    markAsKnown() {
        // 更新统计
        this.stats.learned++;
        this.stats.toReview--;
        
        // 显示提示
        prompt.showToast({
            message: '已掌握！',
            duration: 1000
        });
        
        // 加载下一个单词
        this.loadNextWord();
    },
    
    markAsUnknown() {
        // 显示提示
        prompt.showToast({
            message: '已加入复习',
            duration: 1000
        });
        
        // 加载下一个单词
        this.loadNextWord();
    },
    
    loadNextWord() {
        this.wordIndex = (this.wordIndex + 1) % SAMPLE_WORDS.length;
        this.currentWord = SAMPLE_WORDS[this.wordIndex];
    },
    
    checkAnswer(index) {
        if (index === this.currentReviewWord.correctIndex) {
            // 回答正确
            this.reviewScore++;
            prompt.showToast({
                message: '回答正确！',
                duration: 1000
            });
        } else {
            // 回答错误
            prompt.showToast({
                message: '回答错误，正确答案：' + this.currentReviewWord.correctMeaning,
                duration: 2000
            });
        }
        
        // 加载下一道复习题
        this.loadNextReviewQuestion();
    },
    
    loadNextReviewQuestion() {
        this.currentReviewIndex = (this.currentReviewIndex + 1) % this.reviewWords.length;
        this.currentReviewWord = this.reviewWords[this.currentReviewIndex];
    },
    
    openPhoneApp() {
        syncService.launchPhoneApp().then(result => {
            if (result.success) {
                prompt.showToast({
                    message: result.message,
                    duration: 1000
                });
            } else {
                prompt.showToast({
                    message: result.message || '打开手机应用失败',
                    duration: 2000
                });
            }
        }).catch(error => {
            console.error('打开手机应用失败:', error);
            prompt.showToast({
                message: '打开手机应用失败',
                duration: 2000
            });
        });
    },
    
    // 设置页面相关方法
    increaseDailyGoal() {
        if (this.settings.dailyGoal < 50) {
            this.settings.dailyGoal += 5;
            this.showSettingToast('每日目标已设置为: ' + this.settings.dailyGoal);
        }
    },
    
    decreaseDailyGoal() {
        if (this.settings.dailyGoal > 5) {
            this.settings.dailyGoal -= 5;
            this.showSettingToast('每日目标已设置为: ' + this.settings.dailyGoal);
        }
    },
    
    toggleReminder(e) {
        this.settings.reminderEnabled = e.checked;
        this.showSettingToast(this.settings.reminderEnabled ? '已开启定时提醒' : '已关闭定时提醒');
    },
    
    toggleDarkMode(e) {
        this.settings.darkMode = e.checked;
        this.showSettingToast(this.settings.darkMode ? '已切换到深色模式' : '已切换到浅色模式');
        // 在实际应用中，这里可以更改应用的主题
    },
    
    async changeSyncFrequency() {
        // 循环切换同步频率选项
        this.settings.syncFrequencyIndex = (this.settings.syncFrequencyIndex + 1) % SYNC_FREQUENCIES.length;
        this.settings.syncFrequency = SYNC_FREQUENCIES[this.settings.syncFrequencyIndex];
        
        // 根据索引获取对应的频率值
        let frequency;
        switch (this.settings.syncFrequencyIndex) {
            case 0: frequency = syncService.SyncFrequency.ON_LAUNCH; break;
            case 1: frequency = syncService.SyncFrequency.HOURLY; break;
            case 2: frequency = syncService.SyncFrequency.DAILY; break;
            case 3: frequency = syncService.SyncFrequency.MANUAL; break;
            default: frequency = syncService.SyncFrequency.DAILY;
        }
        
        // 更新同步频率设置
        await syncService.changeSyncFrequency(frequency);
        
        this.showSettingToast('同步频率已设置为: ' + this.settings.syncFrequency);
    },
    
    showSettingToast(message) {
        prompt.showToast({
            message: message,
            duration: 1000
        });
    }
};
